var imageCompress = (function(){

	var imageCompress = function(){

	};

	imageCompress.prototype.init = function(config){
		return this;
	}

	imageCompress.prototype.changeUploadFile = function(e,callback){
		console.log('file change now');
		// console.log(e);
		var files = e.target.files;
		// console.log(files);
		console.log(this.fileSize);

		// $.each(files, function(file) {
		for(var i = 0;i<files.length;i++){
			var file = files[i];
			var reader  = new FileReader();
			reader.onload = function (e){
			  var img = file;
			  this.resizeIMG(img, this.handleBinaryFile(e.target.result), function(imgDom){
			    var returnObj = {fileName: file.name, fileBase64Str: imgDom.src};
			    callback(returnObj);
			  }.bind(this));
			  reader = null;
			}.bind(this);
			reader.readAsArrayBuffer(file);	
		}
		
		// }.bind(this));
	};

	imageCompress.prototype.handleBinaryFile = function(file){
		var dataView = new DataView(file);
		if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
		console.log("Not a valid JPEG");
		return false; // not a valid jpeg
		}
		var offset = 2,
		  length = file.byteLength,
		  marker;

		while (offset < length) {
		if (dataView.getUint8(offset) != 0xFF) {
		  console.log("Not a valid marker at offset " + offset + ", found: " + dataView.getUint8(offset));
		  return false; // not a valid marker, something is wrong
		}
		marker = dataView.getUint8(offset + 1);
		console.log(marker);
		// we could implement handling for other markers here,
		// but we're only looking for 0xFFE1 for EXIF data
		if (marker == 225) {
		  return this.readEXIFData(dataView, offset + 4, dataView.getUint16(offset + 2) - 2);
		} else {
		  offset += 2 + dataView.getUint16(offset+2);
		}
		}
	}


	imageCompress.prototype.getStringFromDB = function (buffer, start, length) {
      var outstr = "";
      for (n = start; n < start+length; n++) {
        outstr += String.fromCharCode(buffer.getUint8(n));
      }
      return outstr;
    };

    imageCompress.prototype.readEXIFData = function (file, start) {
      if (this.getStringFromDB(file, start, 4) != "Exif") {
        return false;
      }
      var bigEnd,
          tags, tag,
          exifData, gpsData,
          tiffOffset = start + 6;
      // test for TIFF validity and endianness
      if (file.getUint16(tiffOffset) == 0x4949) {
        bigEnd = false;
      } else if (file.getUint16(tiffOffset) == 0x4D4D) {
        bigEnd = true;
      } else {
        return false;
      }

      if (file.getUint16(tiffOffset+2, !bigEnd) != 0x002A) {
        return false;
      }

      var firstIFDOffset = file.getUint32(tiffOffset+4, !bigEnd);

      if (firstIFDOffset < 0x00000008) {
        return false;
      }
      tags = this.readTags(file, tiffOffset, tiffOffset + firstIFDOffset, bigEnd);
      file = null;
      return tags;
    };

    imageCompress.prototype.readTags = function (file, tiffStart, dirStart, bigEnd) {
      var entries = file.getUint16(dirStart, !bigEnd),
          tags = {},
          entryOffset, tag,
          i;

      for (i=0;i<entries;i++) {
        entryOffset = dirStart + i*12 + 2;
        if(file.getUint16(entryOffset, !bigEnd) === 274)
          tags['Orientation'] = this.readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd);
      }
      return tags;
    };

    imageCompress.prototype.readTagValue = function (file, entryOffset, tiffStart, dirStart, bigEnd) {
      var type = file.getUint16(entryOffset+2, !bigEnd),
          numValues = file.getUint32(entryOffset+4, !bigEnd),
          valueOffset = file.getUint32(entryOffset+8, !bigEnd) + tiffStart,
          offset,
          vals, val, n,
          numerator, denominator;
      if (type === 3) {
        if (numValues == 1) {
          return file.getUint16(entryOffset + 8, !bigEnd);
        } else {
          offset = numValues > 2 ? valueOffset : (entryOffset + 8);
          vals = [];
          for (n=0;n<numValues;n++) {
            vals[n] = file.getUint16(offset + 2*n, !bigEnd);
          }
          return vals;
        }
      }
    };

    imageCompress.prototype.resizeIMG = function(img, orientation, cb) {
      // console.log(img)
      // console.log(orientation);
      var mpImg = new MegaPixImage(img);
      var resImg = new Image();
      // if ( navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) ) {
      var originalOrientation = orientation.Orientation === 6 ? 6 : orientation.Orientation;
      mpImg.render(resImg, { maxWidth: 1024, maxHeight: 1024, quality: 0.5, orientation: originalOrientation });
      // }else{
      //   mpImg.render(resImg, { maxWidth: 1024, maxHeight: 1024, quality: 0.5});
      // };
      resImg.onload = function() {
        cb(resImg);
        resImg = null;
      }.bind(this)
    };

    return imageCompress;

})()